#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct msgbuf{
	long type; 
	char text[100];
};

int main(void)
{
	int id = msgget(1234, IPC_CREAT|0644); 
	if ( id == -1 ) perror("msgget"),exit(1);
	int pid=vfork();
	if(pid <0)perror("fork"),exit(1);
	else if(pid==0){
		int qid = msgget(1234, 0);
		if ( qid == -1 ) perror("msgget"),exit(1);
		//while(1){
		struct msgbuf sb;
		printf("发送数据\n");
		printf("channel: ");
		scanf("%ld", &sb.type);
		printf("text:");
		scanf("%s", sb.text);
		printf("\n");
			
		if ( msgsnd(id, &sb, strlen(sb.text), 0) == -1 )
			perror("msgsnd"),exit(1);		
		//}
		return 0;
	}
	int qid = msgget(1234, 0);
		if (qid == -1 )
			perror("msgget"),exit(1);
		struct msgbuf sb;
		printf("接收数据\n");
		printf("channel:");
		long num;
		scanf("%ld", &num);
		int r = msgrcv(qid, &sb, 100, num, 0);
		if ( r == -1 ) perror("msgrcv"),exit(1);
		printf("%s\n", sb.text);
		return 0;
}
